<?php

namespace MicroCyanHelper\Core\Kernel\Traits;

use Predis\Client;

class Cache
{
    /**
     * @var string
     */
    protected $prefix = '';
    /**
     * @var Client
     */
    private $redis = null;
    public function __construct(array $config,Client $redis)
    {
        $this->prefix = $config['namespace']??'';
        $this->redis = $redis;
    }

    private function canBeKey($key): bool
    {
        return ( ( is_string($key)&&strlen($key)>0 ) || is_numeric($key) );
    }
    private function canBeValue($value): bool
    {
        return ( is_string($value) || is_numeric($value) );
    }

    /**
     * @param $key
     * @param $value
     * @param $expire_seconds
     * @return bool
     */
    public function set($key='',$value='',$expire_seconds=''): bool
    {
        if ($this->canBeKey($key)&&$this->canBeValue($value)){
            $this->redis->set( $this->prefix.':'.$key,$value);
            if (is_numeric($expire_seconds)&&$expire_seconds>0){
                $this->redis->expire($key,$expire_seconds);
            }
            return true;
        }
        return false;
    }

    /**
     * @param $key
     * @return string
     */
    public function get($key): string
    {
        if ($this->canBeKey($key)){
            return $this->redis->get($this->prefix.':'.$key)??'';
        }
        return '';
    }

    /**
     * @param $key
     * @return false|int
     */
    public function delete($key){
        if ($this->canBeKey($key)){
            return $this->redis->del($this->prefix.':'.$key);
        }
        return false;
    }
}